package mygroup.ldap;

import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.query.ContainerCriteria;
import org.springframework.ldap.query.LdapQueryBuilder;

import static mygroup.ldap.DemoParameters.*;

/**
 * @author gawain.r
 * @create 2020-07-11 18:31
 * @desc a demo for ldap authenticate
 **/
public class LdapApplication {


    public static void main(String[] args) {

        LdapTemplate ldapTemplate = generateLdapTemplate();
        ContainerCriteria query = LdapQueryBuilder.query()
                .base(BASE)
                .where("cn").is(ACCOUNT)
                .and(LdapQueryBuilder.query().where("memberOf").is(GROUP));
        //如果用户不存在，抛出异常  org.springframework.ldap.NameNotFoundException
        //如果密码不正确，抛出异常 org.springframework.ldap.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]
        ldapTemplate.authenticate(
                query,
                PWD);
    }
    private static LdapTemplate generateLdapTemplate() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(LDAP_URL);
//        contextSource.setBase("dc=xxx,dc=yyy,dc=zzz");
        //ldap服务如果配置不允许匿名访问，则需要设置用户和密码
        contextSource.setUserDn(LDAP_USER_DN);
        contextSource.setPassword(LDAP_PASSWORD);
        contextSource.setPooled(true);
        LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
        try {
            //如果使用spring注入管理实例，会自动调用afterPropertiesSet
            contextSource.afterPropertiesSet();
            ldapTemplate.afterPropertiesSet();
        } catch (Exception e) {
            throw new RuntimeException("初始化失败",e);
        }
        return ldapTemplate;
    }
}
